package com.oldroid.apps.getit.ui;

import java.io.File;
import java.net.URLConnection;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.oldroid.apps.getit.R;
import com.oldroid.apps.getit.provider.DownloadsContract.Downloads;
import com.oldroid.apps.getit.provider.DownloadsContract.Downloads_Tags;
import com.oldroid.apps.getit.provider.DownloadsContract.Tags;
import com.oldroid.apps.getit.ui.adapter.DownloadsAdapter;
import com.oldroid.apps.getit.util.AnalyticsUtils;


/**
 * 
 * @author Jervis
 *
 * To Do:
 * -> This class uses the same layout as the downloadsfragment. It should be updated so that it has it's own
 *    layout view whereby essentially when clicked upon, a list of currently available tags is shown. 
 *    Click a tag, opens a new (view / activity ??) where we show the user all files that have that particular tag.
 *    
 *    There already exists a tag_frament layout that can be customized to make this view.
 * 
 *
 */
public class TagsFragment extends Fragment{

	
	private static final String TAG = "DownloadsFragment";
	private LinearLayout mLinearLayout;
	private ListView mListView;
	private TextView mTextView;
	private static String[] PROJECTION = new String[] { Downloads._ID, Downloads.FILENAME, Downloads.URI,
			Downloads.CREATED, Downloads.MODIFIED, Downloads.TOTAL_BYTES, Downloads.STARRED, Downloads.DELETED };
	private static String[] TAGS_PROJECTION = new String[] { Tags._ID, Tags.TAG };
	
	
	public TagsFragment() {
		// TODO Auto-generated constructor stub
	}
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		//AnalyticsUtils.getInstance(getActivity()).trackPageView("/Tags");
	}
	
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_downloads, null);

		root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.FILL_PARENT));
		mLinearLayout = (LinearLayout) root.findViewById(R.id.downloads_tagged_title);
		mListView = (ListView) root.findViewById(R.id.downloads_list);
		mTextView = (TextView) root.findViewById(R.id.downloads_empty_label);

//		if (getArguments().getString("tag_search") == null) {
//			mLinearLayout.setVisibility(View.GONE);
//		} else {
//			mLinearLayout.setVisibility(View.VISIBLE);
//		}
		Cursor cursor = getActivity().getContentResolver().query(Downloads.CONTENT_URI, PROJECTION,
				Downloads.DELETED + "=?", new String[] { "0" }, Downloads.DEFAULT_SORT);
		// Cursor tags_cursor =
		// getActivity().getContentResolver().query(Downloads_Tags.CONTENT_URI,
		// projection, selection, selectionArgs, sortOrder)
		if (cursor.getCount() == 0) {
			// You haven't downloaded yet.
			// Display the float label
			mListView.setVisibility(View.GONE);
			mTextView.setVisibility(View.VISIBLE);
		} else {
			// Display the list
			mTextView.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);

			// SimpleDownloadsAdapter adapter = new
			// SimpleDownloadsAdapter(getActivity(),
			// R.layout.downloads_item_row, cursor, from, to);
			// SimpleCursorAdapter tempAdapter = new
			// SimpleCursorAdapter(getActivity(), R.layout.downloads_item_row,
			// cursor, from, to);
			Cursor tagCursor = getActivity().getContentResolver().query(Tags.CONTENT_URI, TAGS_PROJECTION, null, null, null);
			
			DownloadsAdapter dwnAdapter = new DownloadsAdapter(getActivity(), cursor, tagCursor);
			//dwnAdapter.showTags = true; // enable tags to be shown. 
			
			mListView.setFastScrollEnabled(true); // enable fast scrolling of list.
			mListView.setAdapter(dwnAdapter );
			
			//mListView.setItemsCanFocus(false);
			
			mListView.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> av, View v,
						int position, long id) {
					
					Cursor c = (Cursor) av.getItemAtPosition(position);
						
					//Toast.makeText(getActivity(), "CurPos = " +c.getPosition() + ". Name = " + c.getString(Downloads.COLUMN_INDEX_FILENAME), Toast.LENGTH_SHORT).show(); // debugging
					String filepath = c.getString(Downloads.COLUMN_INDEX_URI);
					
					
					File fp = new File(filepath);
					
					if(!fp.exists())
						return;
					
					try{
						Intent i = new Intent();
						i.setAction(Intent.ACTION_VIEW);
						i.setDataAndType(Uri.fromFile(fp), URLConnection.guessContentTypeFromName(fp.getName()));
						//startActivity(i);
					} catch(ActivityNotFoundException e){
						Toast.makeText(getActivity(), "No program capable of opening that file was found.", Toast.LENGTH_SHORT).show();
						
					}
						
					
				}
			});
			
		}

		return root;

		
	}
	
	
}
